import { clearToken, request } from '@/utils'
import { createSlice } from '@reduxjs/toolkit'
import { setToken as _setToken, getToken } from '@/utils'
import { loginAPI, getProfileAPI } from '@/apis/user'

const userStore = createSlice({
    name: 'user',
    // 数据状态
    initialState: {
        token: getToken() || '',
        userInfo: {}
    },
    // 同步修改方法
    reducers: {
        setToken(state, actions) {
            state.token = actions.payload
            _setToken(actions.payload)
        },
        setUserInfo(state, actions) {
            state.userInfo = actions.payload
        },
        clearUserInfo(state) {
            state.token = ''
            state.userInfo = {}
            clearToken()
        }
    }
})

// 解构出 actionCreater 函数
const { setToken, setUserInfo, clearUserInfo } = userStore.actions

const fetchToken = (loginForm) => async (dispatch) => {
    const res = await loginAPI(loginForm)
    dispatch(setToken(res.data.token))
}

const fetchUserInfo = () => async (dispatch) => {
    const res = await getProfileAPI()
    dispatch(setUserInfo(res.data))
}

export { fetchToken, fetchUserInfo, clearUserInfo }

// 获取 reducer 函数
const userReducer = userStore.reducer

export default userReducer